import 'package:get/get.dart';

import './base_repository.dart';
import '../providers/user_provider.dart';
import '../models/user_model.dart';
import '../models/response/base_response.dart';

/// 用户仓库
/// 负责封装用户数据相关的业务逻辑
class UserRepository extends BaseRepository {
  // 注入依赖
  final UserProvider _userProvider = Get.find<UserProvider>();

  /// 获取当前用户信息
  /// 优先从本地缓存读取，失败或无缓存则从网络获取
  Future<UserModel?> getCurrentUser() async {
    // 尝试从缓存读取（如果实现了缓存逻辑）
    // final cachedUser = await storageService.readObject<UserModel>(
    //   'current_user_profile', 
    //   (json) => UserModel.fromJson(json)
    // );
    // if (cachedUser != null) return cachedUser;

    // 从网络获取
    try {
      final response = await _userProvider.getCurrentUser();
      if (response.isSuccess && response.data != null) {
        // 缓存用户信息（如果需要）
        // await storageService.writeObject('current_user_profile', response.data!);
        return response.data!;
      } else {
        // API 返回错误，但请求成功
        throw Exception(response.message);
      }
    } catch (e) {
      // 网络请求失败或其他异常
      print('获取当前用户信息失败: $e');
      // 可以选择返回 null 或重新抛出异常
      return null; 
    }
  }

  /// 更新用户个人资料
  Future<UserModel> updateUserProfile(String userId, Map<String, dynamic> userData) async {
    final response = await _userProvider.updateUserProfile(userId, userData);
    if (response.isSuccess && response.data != null) {
      // 更新成功，可能需要更新本地缓存
      // await storageService.writeObject('current_user_profile', response.data!);
      return response.data!;
    } else {
      throw Exception(response.message);
    }
  }

  /// 获取用户列表 (带分页)
  Future<List<UserModel>> getUserList({int page = 1, int limit = 10}) async {
    final response = await _userProvider.getUserList(page: page, limit: limit);
    if (response.isSuccess && response.data != null) {
      return response.data!;
    } else {
      // 即使列表为空，isSuccess 也可能为 true，但 data 为空列表 []
      // 如果 API 明确返回错误，则抛出
      if (!response.isSuccess) {
         throw Exception(response.message);
      }
      return []; // 返回空列表
    }
  }

  /// 根据 ID 获取用户信息 (管理员)
  Future<UserModel?> getUserById(String userId) async {
     try {
      final response = await _userProvider.getUserById(userId);
      if (response.isSuccess && response.data != null) {
        return response.data!;
      } else {
        throw Exception(response.message);
      }
    } catch (e) {
      print('获取用户 $userId 信息失败: $e');
      return null; 
    }
  }

  /// 更新用户信息
  Future<UserModel?> updateProfile({
    required String userId,
    String? displayName,
    String? email,
    String? phone,
    String? avatarUrl,
    String? bio,
    String? address,
    String? city,
    String? country,
    String? zipCode,
    Map<String, dynamic>? extraData,
  }) async {
    final response = await _userProvider.updateProfile(
      userId: userId,
      displayName: displayName,
      email: email,
      phone: phone,
      avatarUrl: avatarUrl,
      bio: bio,
      address: address,
      city: city,
      country: country,
      zipCode: zipCode,
      extraData: extraData,
    );
    
    return handleResponse<UserModel?, UserModel>(
      response,
      onSuccess: (data) => data,
      onError: (message, code) => null,
    );
  }
  
  /// 更改密码
  Future<bool> changePassword({
    required String oldPassword,
    required String newPassword,
  }) async {
    final response = await _userProvider.changePassword(
      oldPassword: oldPassword,
      newPassword: newPassword,
    );
    
    return handleResponse<bool, void>(
      response,
      onSuccess: (_) => true,
      onError: (_, __) => false,
    );
  }
  
  /// 获取用户详情
  Future<UserModel?> getUserDetail({
    required String userId,
  }) async {
    final response = await _userProvider.getUserDetail(
      userId: userId,
    );
    
    return handleResponse<UserModel?, UserModel>(
      response,
      onSuccess: (data) => data,
      onError: (_, __) => null,
    );
  }
  
  /// 删除用户
  Future<bool> deleteUser({
    required String userId,
  }) async {
    final response = await _userProvider.deleteUser(
      userId: userId,
    );
    
    return handleResponse<bool, void>(
      response,
      onSuccess: (_) => true,
      onError: (_, __) => false,
    );
  }
  
  /// 激活/停用用户
  Future<UserModel?> toggleUserActive({
    required String userId,
    required bool isActive,
  }) async {
    final response = await _userProvider.toggleUserActive(
      userId: userId,
      isActive: isActive,
    );
    
    return handleResponse<UserModel?, UserModel>(
      response,
      onSuccess: (data) => data,
      onError: (_, __) => null,
    );
  }
  
  /// 更新用户角色
  Future<UserModel?> updateUserRole({
    required String userId,
    required String role,
  }) async {
    final response = await _userProvider.updateUserRole(
      userId: userId,
      role: role,
    );
    
    return handleResponse<UserModel?, UserModel>(
      response,
      onSuccess: (data) => data,
      onError: (_, __) => null,
    );
  }
} 